import { AdTypes } from "./PlatDefine";
import { SdkBase } from "./SdkBase";
import ks_analytics from "./ks_analytics";
import mailiang from "./mailiang";
import * as UserManager from "../scripts/UserManager.js"

/** 网页SDK */

export class SdkKs extends SdkBase {
    private _ks: any = null;
    // constructor() {
    //     super();
     

    // }
    private openId=''
    Init(){
        this._ks =  window["ks"];
        console.log('sdk ks 初始化')
        console.log(this._ks.getLaunchOptionsSync().from,'sdk ks from')
        cc.sys.localStorage.setItem('sceneFrom',this._ks.getLaunchOptionsSync().from)
        this._ks.onShow && this._ks.onShow((res) => {  //从后台返回到游戏
            if(this._ks.isLaunchFromShortcut()){
                // 从桌面进入游戏 
                // 发放奖励
                cc.game.emit('rightPoint')
                cc.sys.localStorage.setItem('rpoint', false)
                UserManager.User.data.key+=1
                UserManager.User.__proto__.save()
                cc.sys.localStorage.setItem(
                    "walkFast" + "_" + "key",
                    JSON.stringify(UserManager.User.data.key)
                  );
                cc.game.emit('event_10')
                // 红点消失
            }
            console.log(res,'onshow res')
        });
        
        this.login(() => { });

    }
    public login(callback: (data: any) => void): void {

        let ks = this._ks;
        // console.log('ks login',this._ks)
        // console.log('ks login2',ks.getLaunchOptionsSync())
        
        this._ks.login({
            success: function (res) {
                console.log(res.code);
                // console.log(this._ks)
                // console.log(this._ks.getLaunchOptionsSync())
                let query = ks.getLaunchOptionsSync().query;
                
                // let appid = "ks656681124015883456"
                // let appid = "ks678917644661367088"
                let appid = "ks701154167624293309"
                ks_analytics.init(appid, res.code,query, 
                    (data) => {
                    console.log("初始化成功", data)
        
                    console.log( data.result.open_id)
                    this.openId = data.result.open_id
                    mailiang.Instance.init(this.openId)

                  }, () => {
                    console.log("初始化失败")
                  })
            },
            fail: function (error) {
                console.log('sdk ks error')
                console.error(error);
            },
            complete: function () {
                console.log("login complete");
            }
        })
    }
    // 创建激励视频
    createRewarded() {
        let param = {
            // adUnitId: "2300012410_01"
            // adUnitId: "2300012505_01"
            adUnitId: "2300012719_01"
        };
        let rewardedVideoAd = this._ks.createRewardedVideoAd(param);
        if (rewardedVideoAd) {
            rewardedVideoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                if (res && res.isEnded) {
                    // 正常播放结束，可以下发游戏奖励

                }
                else {
                    // 播放中途退出，不下发游戏奖励
                }
            })
            rewardedVideoAd.onError(res => {
                // 激励视频广告Error事件
            })
            let p = rewardedVideoAd.show()
            p.then(function (result) {
                // 激励视频展示成功
                console.log(`show rewarded video ad success, result is ${result}`)
            }).catch(function (error) {
                // 激励视频展示失败
                console.log(`show rewarded video ad failed, error is ${error}`)
            })
        } else {
            console.log("创建激励视频组件失败");
        }
    }
    // 创建插屏视频
    createInterstitialAd() {
        let param = {
            // adUnitId:'2300012410_02'
            // adUnitId:'2300012505_02'
            adUnitId:'2300012719_02'
        };
        let interstitialAd = this._ks.createInterstitialAd(param);
        if (interstitialAd) {
            interstitialAd.onClose(res => {
                // 插屏广告关闭事件
            })
            interstitialAd.onError(res => {
                // 插屏广告Error事件
            })
            let p = interstitialAd.show()
            p.then(function (result) {
                // 插屏广告展示成功
                console.log(`show interstitial ad success, result is ${result}`)
            }).catch(function (error) {
                // 插屏广告展示失败
                console.log(`show interstitial ad failed, error is ${error}`)
                if (error.code === -10005) {
                    // 表明当前app版本不支持插屏广告，可以提醒用户升级app版本
                }
            })
        } else {
            console.log("创建插屏广告组件失败");
        }

    }
    /**快手添加到桌面 */
    public addShortcut() {


        this._ks.addShortcut && this._ks.addShortcut({
            success(res) {
                // EventManager.Instance.event(Events.addToDesk, res.code == 1);
                console.log("添加桌面成功");
            },
            fail(err) {
                if (err.code === -10005) {
                    // EventManager.Instance.event(Events.disableDesk);
                    console.log("暂不支持该功能");
                } else {

                    console.log("添加桌面失败", err.msg);
                }
            },
        });

        let res = this._ks.getSystemInfoSync()

        console.log(res.platform)
        if (res.platform == "ios") {
            // EventManager.Instance.event(Events.addToDesk, true);
        }
    }

    /**快手是否已经添加到桌面 */
    public checkShortcut() {
        this._ks.checkShortcut && this._ks.checkShortcut({
            success(res) {
                //根据res.installed 来判断是否添加成功
                console.log("是否已添加快捷方式", res.installed);
                // EventManager.Instance.event(Events.checkOnDesk, res.installed);
            },
            fail(err) {
                if (err.code === -10005) {
                    // EventManager.Instance.event(Events.disableCheckDesk);
                    console.log("暂不支持该功能");
                } else {
                    console.log("检查快捷方式失败", err.msg);
                }
            },
        });
    }
    // 设为常用
    addCommonUse() {
        this._ks.addCommonUse&&this._ks.addCommonUse({
            success() {
                console.log("设为常用成功");
                // 开始发放奖励
                // 红点消失
                
            },
            fail(err) {
                if (err.code === -10005) {
                    console.log("暂不支持该功能");
                } else {
                    console.log("设为常用失败", err.msg);
                }
            },
        });
    }

    // this._ks.login({
    //     success: (res) => {
    //       console.log(res.code);
    //       let query = window["ks"].getLaunchOptionsSync().query
    //       let appid = "对应的appid"
    //     //   ks_analytics.init(appid, res.code, query, (data) => {
    //     //     console.log("初始化成功", data)
    //     //     //获取openid
    //     //     self.openId = data.result.open_id
    //     //     console.log(self.openId)
    //     //   }, () => {
    //     //     console.log("初始化失败")
    //     //   })
    //     },
    //     fail: (error) => {
    //       console.error(error);
    //     },
    //     complete: () => {
    //       console.log("login complete");
    //     }
    //   })
}